import { Persistent, BasicKeys } from '@/utils/cache/persistent';
import { CacheTypeEnum, TOKEN_KEY } from '@/enums/cacheEnum';
import projectSetting from '@/settings/projectSetting';
import { useRoute, useRouter } from 'vue-router';
import { find } from 'lodash-es';
import { getPageAuthAccessList } from '@/api/system/system';

const { permissionCacheType } = projectSetting;
const isLocal = permissionCacheType === CacheTypeEnum.LOCAL;

export function getToken() {
  return getAuthCache(TOKEN_KEY);
}

export function getAuthCache<T>(key: BasicKeys) {
  const fn = isLocal ? Persistent.getLocal : Persistent.getSession;
  return fn(key) as T;
}

export function setAuthCache(key: BasicKeys, value) {
  const fn = isLocal ? Persistent.setLocal : Persistent.setSession;
  return fn(key, value, true);
}

export function clearAuthCache(immediate = true) {
  const fn = isLocal ? Persistent.clearLocal : Persistent.clearSession;
  return fn(immediate);
}

export function fnGetRouterAccessId(): number {
  const aRouterList = useRouter().getRoutes();
  const sPathName = useRoute().name;
  const oFindItem = find(aRouterList, { name: sPathName }) as Recordable;
  if (oFindItem) {
    return oFindItem?.meta.id;
  } else {
    return -1;
  }
}

/**
 * @description 获取访问菜单
 * @returns 访问权限对象
 */
export async function fnApiGetAccessMenu(): Promise<Record<string, any>> {
  const nMenuId = fnGetRouterAccessId();

  if (nMenuId < 0) {
    return {};
  }

  try {
    const { list } = await getPageAuthAccessList({ menu_id: nMenuId });
    return fnChildFormatAccess(list);
  } catch (error) {
    console.error('Error fetching access menu:', error);
    return {};
  }
}

function fnChildFormatAccess(resultData: any) {
  const returnData = {};
  if (Object.prototype.toString.call(resultData) === '[object Array]') {
    resultData.forEach((v) => {
      let sKey = v.auth_code || v.id;
      if (String(sKey).indexOf('tags') >= 0) {
        sKey = 'tags' + String(sKey.replace('tags', ''));
      }
      returnData[sKey] = {
        id: v.id,
        label: v.name,
        show: true,
      };
      if (v.children && v.children.length) {
        returnData[sKey]['child'] = fnChildFormatAccess(v.children);
      }
    });
  } else {
    const sKey = resultData.id;
    returnData[sKey] = { id: resultData.id, label: resultData.name };
  }
  return returnData;
}
